package project02.view;

import project02.domain.CurrentUser;
import project02.domain.Job;
import project02.domain.User;
import project02.service.LoginService;
import project02.service.UserListService;


import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class LoginView {
    {
        File file = new File(UserListService.INFORMATION);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ObjectOutputStream ois = null;
            try {
                ois = new ObjectOutputStream(new FileOutputStream(UserListService.INFORMATION));
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                ois.writeObject(new ArrayList<User>());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public Scanner sc = new Scanner(System.in);
    public LoginService loginService = new LoginService();
    public ArrayList<User> inf = new ArrayList<>();

    //软件初始界面
    public void initMenu() throws IOException, ClassNotFoundException, ParseException, InterruptedException {

        boolean flag = true;
        int i = 0;
        while (flag) {
            System.out.println("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆");
            System.out.println("\t欢迎来到校园兼职中心");
            System.out.println("☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆");
            if (i == 0) {
                System.out.println("\uD83D\uDC15\n\uD83D\uDC15");
                System.out.println("\uD83D\uDC15-----<请先注册或登录>-----\uD83D\uDC15");
                TSUtility.readReturn();
            }
            System.out.print("1.登录\t2.注册\t3.忘记密码\n4.退出\n请选择：");
            char c = TSUtility.readInitMenuSelection();
            switch (c) {
                case '1':
                    loginMenu();
                    flag = false;
                    break;
                case '2':
                    registerMenu();
                    break;
                case '3':
                    System.out.println("请输入用户名：");
                    String name = sc.next();
                    System.out.println("请输入uid：");
                    Integer uid = sc.nextInt();

                    UserListService.getPasswordMenu(name, uid);
                    break;

                case '4':
                    System.out.print("确认是否退出(Y/N)：");
                    char rcs = TSUtility.readConfirmSelection();
                    if (rcs == 'Y') {
                        System.exit(0);
                    }
            }
            i++;
        }
    }


    public void loginMenu() throws IOException, ClassNotFoundException, ParseException, InterruptedException {
        Map<String, Integer> count = new HashMap<>();
        xiaowang: for (;;) {
            System.out.println("====================");
            System.out.println("==\t  登录界面\t  ==");
            System.out.println("====================");
            System.out.println("请输入uid：");
            String uid = sc.next();
            if (count.containsKey(uid) && count.get(uid) >= 5) {
                System.out.println("您的账户已经被停用,洗洗睡吧。");
                continue;
            }
            System.out.println("请输入密码：");
            String password = sc.next();
            if (loginService.login(uid, password)) {
                System.out.println("登录成功！欢迎您！" + uid);
                IndexView.softwareMainMenu();
            } else {
                ObjectInputStream ins = new ObjectInputStream(new FileInputStream(UserListService.INFORMATION));
                ArrayList<User> list = (ArrayList<User>) ins.readObject();
                for (User user : list) {
                    if (user.getUid().equals(uid)) {
                        if (count.containsKey(uid)) {
                            count.put(uid, count.get(uid) + 1);
                            System.out.println("登陆次数还剩" + (5 - count.get(uid)) + "次");
                        } else {
                            count.put(uid, 1);
                            System.out.println("登陆次数还剩" + (5 - count.get(uid)) + "次");

                        }
                        if (count.get(uid) == 5) {
                            user.setAlive(false);
                            System.out.println("登录次数还剩0次，该账户已停用！");
                            ObjectOutputStream ois = new ObjectOutputStream(new FileOutputStream(UserListService.INFORMATION));
                            ois.writeObject(list);
                            ois.flush();
                            ois.close();
                            ins.close();
                        }
                        continue xiaowang;
                    }

                }
                System.out.println("账户未被注册");


//                //如果错误则重新输入，限制次数只有5次，超过次数则程序停止，重新启动
//                System.out.println("登录失败！用户名或密码错误！");
//                if (i == 4) {
//                    System.out.println("登录次数还剩0次，该账户已停用！");
//
//                }else {
//                System.out.println("登录次数还剩" + (4 - i) + "次，请重新输入！");}
//            }
            }
        }
    }

    public void registerMenu() throws IOException, ClassNotFoundException, ParseException, InterruptedException {
       ObjectInputStream ios=new ObjectInputStream(new FileInputStream(UserListService.INFORMATION));
        Scanner sc = new Scanner(System.in);
        ArrayList<User> inf = (ArrayList<User>)ios.readObject();
        System.out.println("====================");
        System.out.println("==\t  注册界面\t  ==");
        System.out.println("====================");

        System.out.println("请输入你要注册的uid：");
        String uid = TSUtility.inputCheck(5,5);
        System.out.println("请输入你要注册的用户名：");
        String name = TSUtility.inputCheck(1,10);
        if (LoginService.register(uid, name)) {
            System.out.println("请输入你的密码(6-12位)：");
            String passWord = TSUtility.inputCheck(1,10);
            System.out.println("请输入你的性别（男/女）：");
            String sex = null;
            do {
                sex= TSUtility.inputCheck(1,1);
                if (!sex.equals("男") &&! sex.equals("女")) {
                    System.out.println("您不知道您是男是女吗？另外这里是中国。请重新输入！");

                }
            }while (!sex.equals("男")&&!sex.equals("女"));
            System.out.println("请输入你的电话：");
            String phone = TSUtility.inputCheck(11,11,"^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$","电话号码输入有误！您是憨批吗？");
            System.out.println("请输入你的学院：");
            String department = null;
            do {
                department= TSUtility.inputCheck(3,20);
                if (!department.endsWith("学院")) {
                    System.out.println("您不知道您的学院吗？滚回去找导师扣分！");
                }
            }while (!department.endsWith("学院"));

            System.out.println("请输入生日，格式‘2020-02-02’");

            String birthday = TSUtility.inputCheck(10, 10,"^(19|20)\\d{2}-(1[0-2]|0?[1-9])-(0?[1-9]|[1-2][0-9]|3[0-1])$","生日格式错误，请重新输入。");
            Date credit_rating=new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println("您的注册时间为："+df.format(credit_rating));

            User temp = new User(uid, name, passWord, sex, phone, department, credit_rating, birthday);
            inf.add(temp);

            FileOutputStream fos = new FileOutputStream(UserListService.INFORMATION);
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(inf);
            os.flush();
            ios.close();

            System.out.println("信息录入完成.");
            fos.close();
            os.close();
        } else {

            initMenu();
        }

//        System.out.println("是否需要修改信息？是（y）");
//        String mod = sc.next();
//        if (mod.equals("y")||mod.equals("Y")) {
//            modifyMenu();
//        } else  {
//            initMenu();
//
//        }
    }


    //用户信息修改界面
    public void modifyMenu() throws IOException, ClassNotFoundException {
        while (true) {
            System.out.println("====================");
            System.out.println("==\t  普通用户修改界面 \t  ==");
            System.out.println("====================");
            System.out.println("请输入你需要修改的类型：");
            System.out.println("1(修改用户名)");
            System.out.println("2(修改密码)");
            System.out.println("3(修改性别)");
            System.out.println("4(修改院系)");
            System.out.println("5(修改生日)");
            System.out.println("6(修改年龄)");
            System.out.println("7(修改电话)");
            System.out.println("8（查询信用等级）");
            System.out.println("9(不修改，退出)");
            char s = TSUtility.readMenuSelection();
            if (s == '1') {
                System.out.println("请输入新的用户名：");
                String name=sc.next();
                loginService.modifyUserInformation(name);

            }
            if (s == '2') {
                System.out.println("请输入新的密码：");
                String newPassWord=sc.next();
               loginService.modifyPassword(newPassWord);


            }
            if (s == '3') {
                System.out.println("请输入新性别：");
                String newSex=sc.next();
                loginService.modifySex(newSex);
            }
            if (s == '4') {
                System.out.println("请输入院系：");
                String dea=sc.next();
                loginService.modifyDepartment(dea);
            }
            if (s == '5') {
                System.out.println("请输入新生日：");
                String newBirthday=sc.next();
                loginService.modifyBirthday(newBirthday);

            }
            if (s == '6') {
                System.out.println("请输入新年龄：");
                Integer newAge=sc.nextInt();
                loginService.modifyAge(newAge);
            }
            if (s == '7') {
                System.out.println("请输入新电话：");
                String newNumber=sc.next();
               loginService.modifyPhone(newNumber);

            }
            if (s == '8') {

                loginService.checkCreditRating();


            }

            if (s == '9') {
                System.out.println("退出中");
                try {
                    TSUtility.loadSpecialEffects();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
}
